<?php

namespace app\common\controller;

use app\Constant\ApiConstant;
use app\service\UserService;
use think\Controller;
use think\facade\Request;
use libs\Redis;

class ApiBase extends Base
{
    public string $token; //用户token

    protected function initialize()
    {
        parent::initialize();
        $this->token = Request::header('token') ?: '';
    }

    /**
     * 封装的接口返回
     * @param int $code 0表示成功，-1表示失败
     * @param string $msg
     * @param array $data
     */
    public function callback($code = 0, $msg = '', $data = [])
    {
        if (empty($msg)) {
            switch ($code) {
                case 0:
                    $msg = '请求成功';
                    break;
                case -1:
                    $msg = '请求失败';
                    break;
            }
        }
        $return = ['code' => $code, 'msg' => $msg, 'data' => $data];
        return json($return);
    }

    public function callbackAndExit($code, $msg = '', $data = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ];
        response(json_encode($result))->contentType('application/json')->send();
        exit;
    }

    /**
     * 检查登录用户与传入的token是否一致
     * @param string $token
     */
    public function checkUserToken(string $token)
    {
        $userinfo = UserService::getJwtUserInfo();
        if ($userinfo['token'] != $token) {
            return '用户信息错误';
        }
        return true;
    }

}
